

import React, { useState, useCallback } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, RefreshControl, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import styles from './styles';
import CCItem from './components/CCItem';

interface CCData {
  id: string;
  title: string;
  applicant: string;
  initiateTime: string;
  status: 'approved' | 'pending' | 'rejected' | 'processing';
  ccTime: string;
  department: string;
  approver?: string;
  currentNode?: string;
  rejectReason?: string;
}

const CC_TO_ME = () => {
  const router = useRouter();
  
  // 状态管理
  const [isSearchVisible, setIsSearchVisible] = useState(false);
  const [isFilterVisible, setIsFilterVisible] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedFilter, setSelectedFilter] = useState('all');
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  
  // 模拟数据
  const [ccDataList, setCcDataList] = useState<CCData[]>([
    {
      id: 'proc-001',
      title: '员工年度调薪申请',
      applicant: '李小红',
      initiateTime: '2024-01-15 14:30',
      status: 'approved',
      ccTime: '2024-01-15 16:20',
      department: 'HR部门审批',
      approver: '王总监',
    },
    {
      id: 'proc-002',
      title: '办公设备采购申请',
      applicant: '王强',
      initiateTime: '2024-01-15 10:15',
      status: 'processing',
      ccTime: '2024-01-15 11:30',
      department: '采购部门审批',
      currentNode: '财务审核',
    },
    {
      id: 'proc-003',
      title: '项目预算调整申请',
      applicant: '陈思',
      initiateTime: '2024-01-14 16:45',
      status: 'pending',
      ccTime: '2024-01-14 17:20',
      department: '项目部审批',
      currentNode: '部门经理审批',
    },
    {
      id: 'proc-004',
      title: '员工培训费用报销',
      applicant: '刘敏',
      initiateTime: '2024-01-14 09:20',
      status: 'approved',
      ccTime: '2024-01-14 11:15',
      department: '财务部审批',
      approver: '张经理',
    },
    {
      id: 'proc-005',
      title: '会议室使用申请',
      applicant: '赵刚',
      initiateTime: '2024-01-13 15:30',
      status: 'rejected',
      ccTime: '2024-01-13 16:45',
      department: '行政部审批',
      rejectReason: '时间冲突',
    },
    {
      id: 'proc-006',
      title: '差旅费用报销申请',
      applicant: '黄丽',
      initiateTime: '2024-01-13 11:20',
      status: 'processing',
      ccTime: '2024-01-13 13:10',
      department: '财务部审批',
      currentNode: '财务复核',
    },
  ]);

  // 筛选选项
  const filterOptions = [
    { id: 'all', label: '全部' },
    { id: 'approved', label: '已通过' },
    { id: 'pending', label: '审批中' },
    { id: 'rejected', label: '已驳回' },
    { id: 'today', label: '今天' },
    { id: 'week', label: '本周' },
  ];

  // 搜索功能
  const handleSearchPress = useCallback(() => {
    setIsSearchVisible(true);
  }, []);

  const handleSearchCancel = useCallback(() => {
    setIsSearchVisible(false);
    setSearchKeyword('');
  }, []);

  // 筛选功能
  const handleFilterPress = useCallback(() => {
    setIsFilterVisible(!isFilterVisible);
  }, [isFilterVisible]);

  const handleFilterSelect = useCallback((filterId: string) => {
    setSelectedFilter(filterId);
  }, []);

  const handleFilterReset = useCallback(() => {
    setSelectedFilter('all');
    setSearchKeyword('');
  }, []);

  // 下拉刷新
  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    // 模拟刷新延迟
    setTimeout(() => {
      setIsRefreshing(false);
    }, 1500);
  }, []);

  // 加载更多
  const handleLoadMore = useCallback(async () => {
    if (isLoadingMore) return;
    
    setIsLoadingMore(true);
    // 模拟加载延迟
    setTimeout(() => {
      setIsLoadingMore(false);
    }, 1000);
  }, [isLoadingMore]);

  // 列表项点击
  const handleCCItemPress = useCallback((processId: string) => {
    router.push(`/p-approval_detail?processInstanceId=${processId}`);
  }, [router]);

  // 数据筛选
  const filteredData = ccDataList.filter(item => {
    const matchesSearch = searchKeyword === '' ||
      item.title.toLowerCase().includes(searchKeyword.toLowerCase()) ||
      item.applicant.toLowerCase().includes(searchKeyword.toLowerCase());

    let matchesFilter = true;
    if (selectedFilter !== 'all' && selectedFilter !== 'today' && selectedFilter !== 'week') {
      matchesFilter = item.status === selectedFilter;
    }

    return matchesSearch && matchesFilter;
  });

  // 渲染列表头部
  const renderListHeader = useCallback(() => (
    <View style={styles.listHeaderContainer}>
      <Text style={styles.listHeaderText}>
        共 <Text style={styles.totalCount}>{filteredData.length}</Text> 条记录
      </Text>
    </View>
  ), [filteredData.length]);

  // 渲染列表尾部
  const renderListFooter = useCallback(() => {
    if (isLoadingMore) {
      return (
        <View style={styles.loadMoreContainer}>
          <FontAwesome6 name="spinner" size={16} color="#969FFF" />
          <Text style={styles.loadMoreText}>加载更多...</Text>
        </View>
      );
    }
    return null;
  }, [isLoadingMore]);

  // 渲染空状态
  const renderEmptyState = useCallback(() => (
    <View style={styles.emptyStateContainer}>
      <View style={styles.emptyStateIcon}>
        <FontAwesome6 name="inbox" size={32} color="#9CA3AF" />
      </View>
      <Text style={styles.emptyStateTitle}>暂无抄送记录</Text>
      <Text style={styles.emptyStateSubtitle}>暂无抄送给您的审批申请</Text>
    </View>
  ), []);

  // 渲染列表项
  const renderCCItem = useCallback(({ item }: { item: CCData }) => (
    <CCItem
      data={item}
      onPress={() => handleCCItemPress(item.id)}
    />
  ), [handleCCItemPress]);

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerTop}>
          <Text style={styles.headerTitle}>抄送我的</Text>
          <View style={styles.headerActions}>
            <TouchableOpacity
              style={styles.headerButton}
              onPress={handleSearchPress}
            >
              <FontAwesome6 name="magnifying-glass" size={18} color="#6B7280" />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.headerButton}
              onPress={handleFilterPress}
            >
              <FontAwesome6 name="filter" size={18} color="#6B7280" />
            </TouchableOpacity>
          </View>
        </View>

        {/* 搜索框 */}
        {isSearchVisible && (
          <View style={styles.searchContainer}>
            <View style={styles.searchInputWrapper}>
              <FontAwesome6 name="magnifying-glass" size={16} color="#6B7280" style={styles.searchIcon} />
              <TextInput
                style={styles.searchInput}
                placeholder="搜索审批标题、发起人..."
                value={searchKeyword}
                onChangeText={setSearchKeyword}
                autoFocus
              />
              <TouchableOpacity onPress={handleSearchCancel}>
                <Text style={styles.searchCancelText}>取消</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}
      </View>

      {/* 筛选面板 */}
      {isFilterVisible && (
        <View style={styles.filterPanel}>
          <View style={styles.filterHeader}>
            <Text style={styles.filterTitle}>筛选条件</Text>
            <TouchableOpacity onPress={handleFilterReset}>
              <Text style={styles.filterResetText}>重置</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.filterGrid}>
            {filterOptions.map((option) => (
              <TouchableOpacity
                key={option.id}
                style={[
                  styles.filterTab,
                  selectedFilter === option.id && styles.filterTabActive
                ]}
                onPress={() => handleFilterSelect(option.id)}
              >
                <Text style={[
                  styles.filterTabText,
                  selectedFilter === option.id && styles.filterTabTextActive
                ]}>
                  {option.label}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      )}

      {/* 抄送列表 */}
      <FlatList
        data={filteredData}
        renderItem={renderCCItem}
        keyExtractor={(item) => item.id}
        ListHeaderComponent={renderListHeader}
        ListFooterComponent={renderListFooter}
        ListEmptyComponent={renderEmptyState}
        contentContainerStyle={styles.listContainer}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            colors={['#969FFF']}
            tintColor="#969FFF"
          />
        }
        onEndReached={handleLoadMore}
        onEndReachedThreshold={0.1}
      />
    </SafeAreaView>
  );
};

export default CC_TO_ME;

